package com.daqian.chance.elastic.search.conf;

import com.daqian.chance.elastic.search.properties.ElasticSearchProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Slf4j
@Configuration
public class ElasticSearchConfig {

    @Autowired
    private ElasticSearchProperties elasticSearchProperties;

    @Bean
    public RestClientBuilder restClientBuilder() {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(elasticSearchProperties.getUsername(), elasticSearchProperties.getPassword()));

        return RestClient.builder(
                new HttpHost(elasticSearchProperties.getHost(), elasticSearchProperties.getPort())).setHttpClientConfigCallback(
                httpAsyncClientBuilder -> httpAsyncClientBuilder.disableAuthCaching().setDefaultCredentialsProvider(credentialsProvider));
    }

    @Bean
    public RestClient restClient() {
        return RestClient.builder(new HttpHost(elasticSearchProperties.getHost(), elasticSearchProperties.getPort(), "http")).build();
    }

    @Bean(destroyMethod = "close")
    public RestClient elasticsearchRestClient(@Autowired RestClientBuilder restClientBuilder) {
        return restClientBuilder.build();
    }

    @Bean(destroyMethod = "close")
    public RestHighLevelClient restHighLevelClient(@Autowired RestClientBuilder restClientBuilder) {
        return new RestHighLevelClient(restClientBuilder);
    }
}
